#include <iostream>
#include <string>
#include <cstdio>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

#define ERR(m)              \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0);

#define DEFAULTPATH "."
#define DEFAULTNAME "fifo"

class fifo
{
public:
    fifo(const std::string &path = DEFAULTPATH, const std::string &name = DEFAULTNAME)
        : _path(path), _name(name)
    {
        _fifoname = path + "/" + name;
    }

    ~fifo()
    {
        int n = unlink(_fifoname.c_str());
        if (n == 0)
        {
            std::cout << "fifo deleted" << std::endl;
        }
        else
            ERR("unlink");
    }

    void CreatFifo()
    {
        int n = mkfifo(_fifoname.c_str(), 0666);
        if (n < 0)
            ERR("mkfifo");
        std::cout << "mkfifo succeess" << std::endl;
    }

    void OpenForWrite()
    {
        // 以写方式打开管道文件
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if (_fd < 0)
            ERR("open");
        std::cout << "open for write succeed!" << std::endl;
    }

    void Write()
    {
        // 写内容到管道文件中
        std::string message;
        std::cout << "please enter->";
        std::cin >> message;
        write(_fd, message.c_str(), message.size());
    }

    void OpenForRead()
    {
        // 以读方式打开管道文件
        // 如果write方没有打开管道文件
        // read方就会在open处阻塞
        // 知道有人打开了管道文件，open才返回
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if (_fd < 0)
            ERR("open");
        std::cout << "open for read succeed!" << std::endl;
    }

    void Read()
    {
        // 从管道文件中读内容
        char buffer[1024];
        int n = read(_fd, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "i get->" << buffer << std::endl;
        }
        else if (n == 0)
        {
            std::cout << "read end of file" << std::endl;
            exit(0);
        }
        else
        {
            ERR("read");
            exit(0);
        }
    }

    void Close()
    {
        close(_fd);
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
    int _fd;
};